package cn.lg.soar.boot.fc.controller;

import cn.lg.soar.boot.client.entity.ClientUser;
import cn.lg.soar.boot.client.entity.vo.ClientUserVo;
import cn.lg.soar.boot.client.service.ClientUserService;
import cn.lg.soar.boot.fc.entity.*;
import cn.lg.soar.boot.fc.entity.vo.RepairSubmitVo;
import cn.lg.soar.boot.fc.entity.vo.RoomVo;
import cn.lg.soar.boot.fc.entity.vo.TenancyRoomVo;
import cn.lg.soar.boot.fc.service.*;
import cn.lg.soar.common.data.msg.I18n;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.core.annotations.IdempotentByParam;
import cn.lg.soar.core.annotations.constraints.group.Create;
import cn.lg.soar.core.annotations.constraints.group.Update;
import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.mvc.enums.ControllerConst;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.mvc.annotations.Log;
import cn.lg.soar.system.auth.entity.Org;
import cn.lg.soar.system.auth.entity.User;
import cn.lg.soar.system.auth.service.IOrgService;
import cn.lg.soar.system.auth.service.IUserService;
import cn.lg.soar.system.general.service.IDictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.lg.soar.database.base.controller.BaseController;

/**
 * 租房表
 * @author ZhuanZ（无密码）
 * @since 2025-01-18
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Api(tags = "租房表")
@Validated
@RestController
@RequestMapping("fc/tenancyRoom")
public class TenancyRoomController extends BaseController<TenancyRoom, TenancyRoomService> {

    @Resource
    private FormItemService formItemService;
    @Resource
    private FormResultService formResultService;
    @Resource
    private RoomService roomService;
    @Autowired
    protected IUserService userService;
    @Autowired
    protected RepairService repairService;
    @Autowired
    protected ProcessApplyService processApplyService;
    /** 客户端用户信息服务 */
    @Autowired private ClientUserService clientUserService;
    @Resource
    private IOrgService orgService;
    @Resource
    private ContractService contractService;

    private SqueryWapper<FormItem> squeryWapper;
    private SqueryWapper<TenancyRoom> tenancyRoomWapper;

    @Override
    protected Serializable getId(TenancyRoom entity) {
        return entity.getId();
    }

    @Log(value = "新增租房表", data = "#p0", dataId = "#$r.data")
    @IdempotentByParam("#p0")
    @ApiOperation(value = ControllerConst.CREATE_NAME)
    @RequestMapping(path = "create", method = RequestMethod.POST)
    public HttpResult<Serializable> create(@RequestBody @Validated(Create.class) TenancyRoom data) {
        return super.createResult(data);
    }

    @Log(value = "修改租房表", data = "#p0", dataId = "#p0.id")
    @ApiOperation(value = ControllerConst.UPDATE_NAME)
    @RequestMapping(path = "update", method = RequestMethod.POST)
    public HttpResult<Void> update(@RequestBody @Validated(Update.class) TenancyRoom data) {
        return super.updateResult(data);
    }

    @Log(value = "删除租房表", data = "#p0")
    @ApiOperation(value = ControllerConst.REMOVE_NAME, notes = "根据 id 删除")
    @RequestMapping(path = "remove", method = RequestMethod.POST)
    public HttpResult<Void> remove(@RequestBody List<Long> ids) {
        return super.removeResult(ids);
    }

    @ApiOperation(value = ControllerConst.DETAIL_NAME, notes = "根据 ID 获取一条数据")
    @RequestMapping(path = "detail", method = RequestMethod.GET)
    public HttpResult<TenancyRoomVo> detail(@RequestParam Long id) {
        TenancyRoom tenancyRoom = super.detailResult(id).getData();
        TenancyRoomVo tenancyRoomVo = new TenancyRoomVo();
        BeanUtils.copyProperties(tenancyRoom, tenancyRoomVo);
        RoomVo roomVo = roomService.getVoData(tenancyRoom.getRoomId());
        String roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
        tenancyRoomVo.setRoomInfo(roomInfo);

//        User user = userService.getById(tenancyRoom.getUserId());
        ClientUser user = clientUserService.getById(tenancyRoom.getUserId());
        if(user != null) {
            tenancyRoomVo.setUserName(user.getUserName());
        }
        tenancyRoomVo.setArea(roomVo.getArea());
        tenancyRoomVo.setLivingRoom(roomVo.getLivingRoom());
        tenancyRoomVo.setOrient(roomVo.getOrient());
        tenancyRoomVo.setOwnershipCode(roomVo.getOwnershipCode());
        tenancyRoomVo.setContacts(roomVo.getContacts());
        tenancyRoomVo.setPhone(roomVo.getPhone());
        return HttpResult.data(tenancyRoomVo);
    }

    @ApiOperation(value = ControllerConst.QUERY_NAME, notes = "多功能查询（分页、列表、统计）")
    @RequestMapping(path = "query", method = RequestMethod.GET)
    public HttpResult<PageResult<TenancyRoomVo>> query(PageQuery pageQuery, QueryParams params){
        params.setFields(new ArrayList<>());
        PageResult<TenancyRoomVo> pageResult = new PageResult<>();
        List<TenancyRoomVo> list = new ArrayList<>();
        List<TenancyRoom> tenancyRoomQuery = super.queryResult(pageQuery, params).getData().getList();
        for (TenancyRoom tenancyRoom : tenancyRoomQuery) {
            TenancyRoomVo tenancyRoomVo = new TenancyRoomVo();
            BeanUtils.copyProperties(tenancyRoom, tenancyRoomVo);
            RoomVo roomVo = roomService.getVoData(tenancyRoom.getRoomId());
            String roomInfo = "";
            if(roomVo != null) {
                roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                        +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
            }
            tenancyRoomVo.setRoomInfo(roomInfo);

//            User user = userService.getById(tenancyRoom.getUserId());
            ClientUser user = clientUserService.getById(tenancyRoom.getUserId());
            if(user != null) {
                tenancyRoomVo.setUserName(user.getUserName());
            }
            tenancyRoomVo.setArea(roomVo.getArea());
            tenancyRoomVo.setLivingRoom(roomVo.getLivingRoom());
            tenancyRoomVo.setOrient(roomVo.getOrient());
            tenancyRoomVo.setOwnershipCode(roomVo.getOwnershipCode());
            tenancyRoomVo.setContacts(roomVo.getContacts());
            tenancyRoomVo.setPhone(roomVo.getPhone());
            list.add(tenancyRoomVo);
        }
        pageResult.setList(list);
        return HttpResult.data(pageResult);
    }

    @Log(value = "导出租房表")
    @ApiOperation(value = ControllerConst.EXPORT_NAME)
    @RequestMapping(path = "export", method = RequestMethod.GET)
    public void exports(String filename, QueryParams params, HttpServletResponse resp){
        super.exportExcel(filename, params, resp);
    }

    @Log(value = "导入租房表")
    @ApiOperation(value = ControllerConst.IMPORT_NAME)
    @RequestMapping(path = "import", method = RequestMethod.POST)
    public HttpResult<Void> imports(HttpServletRequest req){
        return super.importExcel(req);
    }

    @Log(value = "申请租房")
    @ApiOperation(value = "申请租房")
    @PostMapping("/applyRoom")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "userId",value = "用户ID",dataType = "Long",required = true),
            @ApiImplicitParam(name = "collectId",value = "表单收集ID",dataType = "Long",required = true),
            @ApiImplicitParam(name = "roomId",value = "房间ID",dataType = "Long",required = true),
            @ApiImplicitParam(name = "processData",value = "提交表单信息(json字符串)",dataType = "String",required = true)
    })
    public HttpResult<Void> applyRoom(Long userId,Long collectId,Long roomId,String processData) {
//        String processData = "{'field2':'彭笙1','field3':'27','field4':'知青'}";
        List formContentConfigList = new ArrayList();

        if (squeryWapper == null) {
            squeryWapper = new SqueryWapper<>(FormItem.class);
        }
        QueryWrapper<FormItem> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("collectId-eq~"+collectId);
        List<String> orderBy = new ArrayList<>();
        orderBy.add("sort");
        squeryWapper.setWhere(f, wrapper);
        squeryWapper.setOrderBy(orderBy, wrapper);
        List<FormItem> list1 = formItemService.list(wrapper);
        for (FormItem item : list1) {
            formContentConfigList.add(item.getFormItemConfig());
        }

        FormResult formResult = new FormResult();
        formResult.setCollectId(collectId);
        formResult.setSubmitApplicantId(3L);
        formResult.setSubmitUserId(userId);
        formResult.setProcessData(processData);
        formResult.setFormContentConfig(formContentConfigList.toString());
        formResultService.submitForm(formResult,roomId,null);
        return HttpResult.success();
    }

    @Log(value = "合同签订")
    @ApiOperation(value = "合同签订")
    @PostMapping("/contractSign")
    public HttpResult<Void> contractSign(@RequestParam Long id) {
        return contractService.generateContract(id);
    }

    @Log(value = "租房到期")
    @ApiOperation(value = "租房到期")
    @PostMapping("/mature")
    public HttpResult<Void> mature(@RequestParam Long id) {
        return super.service.mature(id);
    }

    @Log(value = "续租申请")
    @ApiOperation(value = "续租申请")
    @PostMapping("/continueApply")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "tenancyId",value = "租房ID",dataType = "Long",required = true)
    })
    public HttpResult<Void> continueApply(@RequestParam Long tenancyId) {
        return super.service.continueApply(tenancyId);
    }

    @Log(value = "续租审核")
    @ApiOperation(value = "续租审核")
    @PostMapping("/continueExamine")
    public HttpResult<Void> continueExamine(@RequestBody @Valid TenancyRoom tenancyRoom) {
        return super.service.continueExamine(tenancyRoom.getId(),tenancyRoom.getContinueState());
    }

    @Log(value = "退租申请")
    @ApiOperation(value = "退租申请")
    @PostMapping("/exitTenancy")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "tenancyId",value = "租房ID",dataType = "Long",required = true)
    })
    public HttpResult<Void> exitTenancy(@RequestParam Long tenancyId) {
        return super.service.exitTenancyApply(tenancyId);
    }

    @Log(value = "报修申请")
    @ApiOperation(value = "报修申请")
    @PostMapping("/repair")
    public HttpResult<Void> repair(@RequestBody @Valid RepairSubmitVo repair) {
        return repairService.repair(repair);
    }

    @Log(value = "转租申请")
    @ApiOperation(value = "转租申请")
    @PostMapping("/subletApply")
    public HttpResult<Void> subletApply(@RequestParam Long id, @RequestParam String account) {
        return super.service.subletApply(id,account);
    }

    @ApiOperation(value = "申请租房详情", notes = "根据 ID 获取一条数据")
    @RequestMapping(path = "tenancyRoomDetail", method = RequestMethod.GET)
    public HttpResult<TenancyRoomVo> tenancyRoomDetail(@RequestParam Long processApplyId) {
        ProcessApply processApply = processApplyService.getById(processApplyId);
        if(processApply == null) {
            return HttpResult.fail("B0000", I18n.build("申请为空！"));
        }
        if(processApply.getTenancyRoomId() == null){
            return HttpResult.fail("B0000", I18n.build("租房信息为空！"));
        }

        TenancyRoom tenancyRoom = super.detailResult(processApply.getTenancyRoomId()).getData();
        TenancyRoomVo tenancyRoomVo = new TenancyRoomVo();
        BeanUtils.copyProperties(tenancyRoom, tenancyRoomVo);
        RoomVo roomVo = roomService.getVoData(tenancyRoom.getRoomId());
        String roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
        tenancyRoomVo.setRoomInfo(roomInfo);

//        User user = userService.getById(tenancyRoom.getUserId());
        ClientUser user = clientUserService.getById(tenancyRoom.getUserId());
        if(user != null) {
            tenancyRoomVo.setUserName(user.getUserName());
        }
        if(tenancyRoom.getSubletUserId() != null){
//            User subletUser = userService.getById(tenancyRoom.getSubletUserId());
            ClientUser subletUser = clientUserService.getById(tenancyRoom.getSubletUserId());
            if(subletUser != null) {
                tenancyRoomVo.setSubletUserName(subletUser.getUserName());
            }
        }
        tenancyRoomVo.setArea(roomVo.getArea());
        tenancyRoomVo.setLivingRoom(roomVo.getLivingRoom());
        tenancyRoomVo.setOrient(roomVo.getOrient());
        tenancyRoomVo.setOwnershipCode(roomVo.getOwnershipCode());
        tenancyRoomVo.setContacts(roomVo.getContacts());
        tenancyRoomVo.setPhone(roomVo.getPhone());
        return HttpResult.data(tenancyRoomVo);
    }

    @ApiOperation(value = "申请租房详情", notes = "根据 ID 获取一条数据")
    @RequestMapping(path = "tenancyRoomDetail1", method = RequestMethod.GET)
    public HttpResult<TenancyRoomVo> tenancyRoomDetail1(@RequestParam Long processApplyId) {
        ProcessApply processApply = processApplyService.getById(processApplyId);
        if(processApply == null) {
            return HttpResult.fail("B0000", I18n.build("租房申请为空！"));
        }

        if (tenancyRoomWapper == null) {
            tenancyRoomWapper = new SqueryWapper<>(TenancyRoom.class);
        }
        QueryWrapper<TenancyRoom> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("formApplyId-eq~"+processApplyId);
        tenancyRoomWapper.setWhere(f, wrapper);
        List<TenancyRoom> list = super.service.list(wrapper);
        if(list.size() <= 0){
            return HttpResult.fail("B0000", I18n.build("租房信息不存在！"));
        }

        TenancyRoom tenancyRoom = list.get(0);
        TenancyRoomVo tenancyRoomVo = new TenancyRoomVo();
        BeanUtils.copyProperties(tenancyRoom, tenancyRoomVo);
        RoomVo roomVo = roomService.getVoData(tenancyRoom.getRoomId());
        String roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
        tenancyRoomVo.setRoomInfo(roomInfo);

//        User user = userService.getById(tenancyRoom.getUserId());
        ClientUser user = clientUserService.getById(tenancyRoom.getUserId());
        if(user != null) {
            tenancyRoomVo.setUserName(user.getUserName());
        }
        tenancyRoomVo.setArea(roomVo.getArea());
        tenancyRoomVo.setLivingRoom(roomVo.getLivingRoom());
        tenancyRoomVo.setOrient(roomVo.getOrient());
        tenancyRoomVo.setOwnershipCode(roomVo.getOwnershipCode());
        tenancyRoomVo.setContacts(roomVo.getContacts());
        tenancyRoomVo.setPhone(roomVo.getPhone());
        return HttpResult.data(tenancyRoomVo);
    }

    @ApiOperation(value = "我的房源")
    @RequestMapping(path = "housingList", method = RequestMethod.GET)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "userId",value = "用户ID",dataType = "Long",required = true),
            @ApiImplicitParam(name = "housingType",value = "查询类型(0-我的房源 1-历史房源)",dataType = "Integer",required = true)
    })
    public HttpResult<PageResult<TenancyRoomVo>> housingList(PageQuery pageQuery,Long userId,Integer housingType){
        QueryParams params = new QueryParams();
        List<String > f = new ArrayList<>();
        f.add("userId-eq~"+userId);
        if(housingType == 0){
            f.add("tenancyState-eq~3");
        }
        params.setF(f);

        PageResult<TenancyRoomVo> pageResult = new PageResult<>();
        List<TenancyRoomVo> list = new ArrayList<>();
        List<TenancyRoom> tenancyRoomQuery = super.queryResult(pageQuery, params).getData().getList();
        for (TenancyRoom tenancyRoom : tenancyRoomQuery) {
            TenancyRoomVo tenancyRoomVo = new TenancyRoomVo();
            BeanUtils.copyProperties(tenancyRoom, tenancyRoomVo);
            RoomVo roomVo = roomService.getVoData(tenancyRoom.getRoomId());
            String roomInfo = "";
            if(roomVo != null) {
                roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                        +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
            }
            tenancyRoomVo.setRoomInfo(roomInfo);

//            User user = userService.getById(tenancyRoom.getUserId());
            ClientUser user = clientUserService.getById(tenancyRoom.getUserId());
            if(user != null) {
                tenancyRoomVo.setUserName(user.getUserName());
            }
            tenancyRoomVo.setArea(roomVo.getArea());
            tenancyRoomVo.setLivingRoom(roomVo.getLivingRoom());
            tenancyRoomVo.setOrient(roomVo.getOrient());
            tenancyRoomVo.setOwnershipCode(roomVo.getOwnershipCode());
            tenancyRoomVo.setContacts(roomVo.getContacts());
            tenancyRoomVo.setPhone(roomVo.getPhone());
            list.add(tenancyRoomVo);
        }
        pageResult.setList(list);
        return HttpResult.data(pageResult);
    }

    @ApiOperation(value = "申请用户详情", notes = "根据 ID 获取一条数据")
    @RequestMapping(path = "clientUserDetail", method = RequestMethod.GET)
    public HttpResult<ClientUserVo> clientUserDetail(@RequestParam Long processApplyId) {
        ProcessApply processApply = processApplyService.getById(processApplyId);
        if(processApply == null) {
            return HttpResult.fail("B0000", I18n.build("租房申请为空！"));
        }
        ClientUser user = clientUserService.getById(processApply.getApplicantId());
        ClientUserVo vo = new ClientUserVo();
        if(user != null) {
            BeanUtils.copyProperties(user, vo);
            if(user.getOrgId() != null){
                Org org = orgService.getById(user.getOrgId());
                if(org != null){
                    vo.setOrgName(org.getName());
                }
            }
        }
        return HttpResult.data(vo);
    }

}